<?php


namespace app\admin\controller\upload;


use app\admin\annotation\UseAuth;
use app\admin\controller\BaseController;
use app\common\http\exception\AppException;
use app\common\model\File;
use app\common\model\FileGroup;
use think\facade\App;

/**
 * Class ImageController
 * @package app\admin\controller\upload
 * @UseAuth(policy="Upload")
 */
class ImageController extends BaseController
{
    /**
     * 图片上传
     * @throws AppException
     * @route('admin/upload/image', 'post')
     */
    public function index()
    {
        $file = $this->request->file('file');
        if (!$file) {
            throw new AppException('文件数据为空');
        }
        $group_id = $this->request->post('group_id/d', 0, 'intval');
        if ($group_id && !FileGroup::where('id', $group_id)->value('id')) {
            throw new AppException('分组不存在');
        }
        $base_path = '/uploads/images/';
        $info = $file
            ->validate([
                'size'=>5242880,
                'ext'=>'jpg,png'
            ])
            ->move(App::getRootPath() . $base_path);
        if (!$info) {
            throw new AppException($file->getError());
        }
        $src = str_replace('\\', '/', $base_path . $info->getSaveName());

        $file = File::create([
            'group_id'=>$group_id,
            'type'=>'image',
            'filename'=>$info->getFilename(),
            'mime'=>$info->getMime(),
            'src'=>$src,
        ]);

        return $this->success($file);
    }


    /**
     * 图片相册列表
     * @return mixed
     * @throws \think\exception\DbException
     * @route('admin/upload/images', 'get')
     */
    public function list()
    {
        $group_id = $this->request->get('group_id/d', 0, 'intval');
        $result = File::where('group_id', $group_id)
            ->where('type', 'image')
            ->order('create_time', 'desc')
            ->paginate();

        return $result->render();
    }

}
